package com.example.guetgreen;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.ref.WeakReference;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MainActivity extends AppCompatActivity {

    private EditText acc,ed1;
    public static final int REQUEST_CODE_CHOOSE=0;
    public static final int REQUEST_CODE_TAKE = 1;
    public static final int RESULT_OK=1;
    private final static int PHOTO_REQUEST_CAMERA = 10;//相机权限请求
    private final static int PHOTO_REQUEST_ALBUM = 20;//相册权限请求
    private final static int CAMERA_REQUEST_CODE = 100;//相机跳转code
    private final static int ALBUM_REQUEST_CODE = 200;//相册跳转code
    private final static int TAILOR_REQUEST_CODE = 300;//图片剪裁code
    private final static String SAVE_AVATAR_NAME = "head.jpg";//需要上传的图片的文件名
    private Uri imageUri;//需要上传的图片的Uri
    private ImageView ivAvatar;
    private Context context = MainActivity.this;
    private String imageBase64;
    private static final String TAG = "tag";
    public static final String MESSAGE_STRING = "com.example.code04.MESSAGE";
    private Handler mHandler;
    private static final int MSG_UPDATE_CURRENT_TIME = 1;
    private TextView tv_time;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        acc = (EditText) findViewById(R.id.ed);
        ed1=(EditText) findViewById(R.id.ed1);
        ivAvatar = findViewById(R.id.iv_avatar);
        SharedPreferences pref = PreferenceManager
                .getDefaultSharedPreferences(this);
        SharedPreferences.Editor editor = pref.edit();
        tv_time = (TextView) this.findViewById(R.id.id_time);
        mHandler = new MyHandler(this);
        mHandler.sendEmptyMessageDelayed(MSG_UPDATE_CURRENT_TIME, 500);
        try{
            String account = pref.getString("ss", "");
            String ed=pref.getString("ee","");
            acc.setText(account);
            ed1.setText(ed);
        }catch (Exception e){
            acc.setText("花江检查点");
            ed1.setText("**一可以通行");
        }

    }
    public void setacc(View view){
        SharedPreferences pref = PreferenceManager
                .getDefaultSharedPreferences(this);
        SharedPreferences.Editor editor = pref.edit();
        String ed=ed1.getText().toString();
        String account=acc.getText().toString();
        if(ed!=null){
            editor.putString("ee",ed);
            Toast.makeText(MainActivity.this, ed, Toast.LENGTH_SHORT).show();
        }
        if(account!=null) {
            editor.putString("ss", account);
            Toast.makeText(MainActivity.this, account, Toast.LENGTH_SHORT).show();
        }
        editor.apply();
        account = pref.getString("ss", "");
        ed=pref.getString("ee","");
        acc.setText(account);
        ed1.setText(ed);
    }

    public void choosePhoto(View view) {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
            // 真正的去打开相册
            openAlbum();
        } else {
            // 去申请权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
        }
    }

    private void openAlbum() {
        /*Intent intent = new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");*/
        Intent intent = new Intent(Intent.ACTION_PICK, null);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(intent, ALBUM_REQUEST_CODE);
    }

    /**
     * 跳转裁剪
     */
    private void openCrop(Uri uri){
        File outfile = new File(getExternalCacheDir(), "imageOut.jpeg");
        try{
            if(outfile.exists()){
                outfile.delete();
                Log.e(TAG, "图片文件存在：" + outfile.getAbsolutePath());
            }
            outfile.createNewFile();
        }catch (IOException e){
            e.printStackTrace();
        }
        imageUri=Uri.fromFile(outfile);

        /*if(Build.VERSION.SDK_INT>=24){
            imageUri=FileProvider.getUriForFile(MainActivity.this,"com.example.camera.fileprovider",outfile);
        }else{
            imageUri=Uri.fromFile(outfile);
        }*/
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) && context != null){
            Log.e(TAG, "裁剪图片存放路径：" + outfile.getAbsolutePath());
        }
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        intent.setDataAndType(uri, "image/*");
        // 设置裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // 裁剪后输出图片的尺寸大小
        intent.putExtra("outputX", 250);
        intent.putExtra("outputY", 250);
        //适配Android10，
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        // 图片格式
        /*
        intent.putExtra("outputFormat", "PNG");
        intent.putExtra("noFaceDetection", true);// 取消人脸识别
        intent.putExtra("return-data", true);// true:不返回uri，false：返回uri
        */
        startActivityForResult(intent, TAILOR_REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == -1){
            //回调成功
            switch (requestCode) {
                case CAMERA_REQUEST_CODE:
                    //相机回调
                    Log.e(TAG, "相机回调");
                    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                        //照片裁剪
                        openCrop(imageUri);
                    } else {
                        Toast.makeText(context, "未找到存储卡", Toast.LENGTH_SHORT).show();
                    }
                    break;
                case ALBUM_REQUEST_CODE:
                    //相册回调
                    Log.e(TAG, "相册回调");
                    if (data != null && data.getData() != null) {
                        Log.e(TAG, "图片data.getData：" + data.getData());
                        openCrop(data.getData());
                        //image.setImageURI(data.getData());
                        //如果需要上传操作的可以使用这个方法
                        //File file = FileUtils.uriToFile(data.getData(), context);
                        //这里的file就是需要上传的图片了
                    }
                    break;
                case TAILOR_REQUEST_CODE:
                    //图片剪裁回调
                    Log.e(TAG, "图片剪裁回调");
//                    Glide.with(context).load(file).into(image);
                    Uri uri = imageUri;
                    Log.e(TAG, "裁剪图片uri" + uri+"imageUri"+imageUri);
                    ivAvatar.setImageURI(uri);
                    //如果需要上传全局的这个file就是需要上传的图片了
                    //File file = this.file;
                    break;
            }
        } else {
            Toast.makeText(context, "取消", Toast.LENGTH_SHORT).show();
        }
    }

    /*
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_TAKE) {
            if (resultCode == RESULT_OK) {
                // 获取拍摄的照片
                try {
                    InputStream inputStream = getContentResolver().openInputStream(imageUri);
                    Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                    ivAvatar.setImageBitmap(bitmap);
                    String imageToBase64 = ImageUtil.imageToBase64(bitmap);
                    imageBase64 = imageToBase64;
                } catch (FileNotFoundException e) {

                }
            }
        } else if (requestCode == REQUEST_CODE_CHOOSE) {

            if (Build.VERSION.SDK_INT < 19) {
                handleImageBeforeApi19(data);
            } else {
                handleImageOnApi19(data);
            }

        }
    }*/

    private void handleImageBeforeApi19(Intent data) {
        Uri uri = data.getData();
        String imagePath = getImagePath(uri, null);
        displayImage(imagePath);
    }

    @TargetApi(19)
    private void handleImageOnApi19(Intent data) {
        String imagePath = null;
        Uri uri = data.getData();
        if (DocumentsContract.isDocumentUri(this, uri)) {
            String documentId = DocumentsContract.getDocumentId(uri);

            if (TextUtils.equals(uri.getAuthority(), "com.android.providers.media.documents")) {
                String id = documentId.split(":")[1];
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);

            } else if (TextUtils.equals(uri.getAuthority(), "com.android.providers.downloads.documents")) {
                if (documentId != null && documentId.startsWith("msf:")) {
                    resolveMSFContent(uri, documentId);
                    return;
                }
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(documentId));
                imagePath = getImagePath(contentUri, null);
            }

        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            imagePath = getImagePath(uri, null);
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            imagePath = uri.getPath();
        }

        displayImage(imagePath);
    }

    private String getImagePath(Uri uri, String selection) {//获取图片地址
        String path = null;
        Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();//游标？
        }
        return path;
    }

    private void displayImage(String imagePath) {//根据图片地址获取图片
        Log.d(TAG, "displayImage: ------------" + imagePath);
        if (imagePath != null) {
            Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
            ivAvatar.setImageBitmap(bitmap);//将获取的图片设置为显示图片
            String imageToBase64 = ImageUtil.imageToBase64(bitmap);
            imageBase64 = imageToBase64;
        }
    }


    private void resolveMSFContent(Uri uri, String documentId) {

        File file = new File(getCacheDir(), "temp_file" + getContentResolver().getType(uri).split("/")[1]);

        try {
            InputStream inputStream = getContentResolver().openInputStream(uri);

            OutputStream outputStream = new FileOutputStream(file);

            byte[] buffer = new byte[4 * 1024];
            int read;
            while ((read = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, read);
            }
            outputStream.flush();

            Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
            ivAvatar.setImageBitmap(bitmap);
            imageBase64 = ImageUtil.imageToBase64(bitmap);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    private static class MyHandler extends Handler {
        private WeakReference<MainActivity> mActivity;

        public MyHandler(MainActivity activity) {
            mActivity = new WeakReference<MainActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            MainActivity activity = mActivity.get();
            switch (msg.what) {
                case MSG_UPDATE_CURRENT_TIME:
                    activity.updateCurrentTime();
                    sendEmptyMessageDelayed(MSG_UPDATE_CURRENT_TIME, 10);
                    break;


                default:
                    break;
            }
        }
    }

    private void updateCurrentTime() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("  HH:mm:ss:SS");
        Date curDate = new Date(System.currentTimeMillis());
        String time = simpleDateFormat.format(curDate);
        tv_time.setText(time);
    }

}